# coding=utf-8
# import time
from django.http.response import JsonResponse, HttpResponse
from django.views.decorators.http import require_GET, require_POST

# from api.models import DeviceData
import requests
from hashlib import md5

SMS_USER = 'heimaojingzhang'
SMS_KEY = 'ZpalBug1HYDvepotVwGB1Awulgz2gqGg'


@require_GET
def get_data(req):
    """
    获取心跳,位置等数据`
    """
    start = int(req.GET.get('start', 0))
    end = int(req.GET.get('end', 0))
    device_id = req.GET.get('device_id')
    datas = DeviceData.objects.filter(device_id=device_id)
    if not start:
        start = time.time() - 24 * 3600
    datas = datas.filter(timestamp__gt=start)
    if end:
        datas = datas.filter(timestamp__lt=end)
    data = [data.to_dict() for data in datas]
    return JsonResponse(data, safe=False)


@require_GET
def alert(req):
    device_id = req.GET.get('device_id', '')
    # TODO: 发送震动和蜂鸣
    return HttpResponse('ok')


def generate_md5(fp):
    m = md5()
    m.update(fp)
    return m.hexdigest()


def send():
    url = 'http://sendcloud.sohu.com/smsapi/send'
    param = {
        'smsUser': SMS_USER,
        'templateId': 3402,
        # 'phone': 17182718892,
        'phone': 18062596910,
        'vars': {'content': '测试数据'}
    }

    param_keys = list(param.keys())
    param_keys.sort()

    param_str = ""
    for key in param_keys:
        param_str += key + '=' + str(param[key]) + '&'
    param_str = param_str[:-1]
    print param_str
    sign_str = SMS_KEY + '&' + param_str + '&' + SMS_KEY
    sign = generate_md5(sign_str)

    param['signature'] = sign

    res = requests.post(url, data=param)
    print res.text


if __name__ == '__main__':
    # sendx()
    send()
